package com.jy.api.okhttp;

import com.google.common.collect.Maps;
import com.jy.api.hospital.dto.HospitalDTO;
import com.jy.api.hospital.dto.JiGouDTO;
import com.jy.api.hospital.dto.ZhiGongDetailDTO;
import com.jy.framework.base.entity.Page;
import com.jy.framework.base.entity.Result;
import com.jy.rhin.config.HospitalConfig;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * 机构及职工 实现客户端
 *@className(类名称):  HospitalClient
 *@description(类描述):
 *@author(创建人):  zsh
 *@createDate(创建时间):  2024年8月5日 上午10:30:24
 *@updateUser(修改人):  zsh
 *@updateDate(修改时间):  2024年8月5日 上午10:30:24
 *@updateRemark(修改备注):
 *@version(版本):  v1.0
 */
@Slf4j
@Component("HospitalClient")
public class HospitalClient extends AbstractThirdClient {

    @Autowired
    private HospitalConfig hospitalConfig;

    public HospitalClient(@Qualifier("okHttpTemplate") RestTemplate restTemplate) {
        super(restTemplate);
    }

    public HospitalConfig getHospitalConfig() {
		return hospitalConfig;
	}

	public void setHospitalConfig(HospitalConfig hospitalConfig) {
		this.hospitalConfig = hospitalConfig;
	}

    @Override
    public String name() {
        return "HospitalClient";
    }

    /**
	 * 互联互通 编辑机构信息
	 * @param jiGouDTO 机构信息
	 * @return
	 */
	public Result<String> huLianHTJG(JiGouDTO jiGouDTO) {
		String url = hospitalConfig.getUrl().getEditOrgPath();

		String orgInfo = JSONUtil.toJsonStr(JSONUtil.parseObj(jiGouDTO));
		log.debug("发起远程http 互联互通 编辑机构信息：{}=>{}", url, orgInfo);
		ResponseEntity<String> responseEntity = execute(url, null, HttpMethod.POST, MediaType.APPLICATION_JSON, orgInfo, Maps.newHashMap());
		String message = this.verify(responseEntity);
		if (StringUtils.isNotBlank(message)) {
			log.error("发起远程http 互联互通 编辑机构信息：{}", message);
			return Result.fail(message);
		}
		JSONObject jsonObject = JSONUtil.parseObj(responseEntity.getBody());
		String data = jsonObject.getStr("data");
		return Result.success(data);
	}

	/**
	 * 机构信息列表(互联互通专用)
	 * @param id 预存查询的唯一编号
	 * @param hospitalId 医疗机构编码（医疗卫生服务机构标识）
	 * @param hospitalName  医疗机构名称
	 * @param status 医疗机构状态
	 * @param jiGouFL 医疗机构分类
	 * @param jiGouFLMC 医疗机构分类名称
	 * @param jiGouFLFS 医疗机构分类方式
	 * @param address 医疗机构地址
	 * @param mobile 医疗机构通讯号
	 * @param from 信息条目起始数
	 * @param maxCount 查询信息最大条数
	 * @return
	 */
	public Result<Page<JiGouDTO>> pageJiGouRhin(String id, String hospitalId, String hospitalName, String status, String jiGouFL, String jiGouFLMC, String jiGouFLFS, String address, String mobile, Integer from,	Integer maxCount) {
		String url = hospitalConfig.getUrl().getSelectOrgPath();
        Map<String, Object> uriVariables = Maps.newHashMap();
        uriVariables.put("id", id);
        uriVariables.put("hospitalId", hospitalId);
        uriVariables.put("hospitalName", hospitalName);
        uriVariables.put("status", status);
        uriVariables.put("jiGouFL", jiGouFL);
        uriVariables.put("jiGouFLMC", jiGouFLMC);
        uriVariables.put("jiGouFLFS", jiGouFLFS);
        uriVariables.put("address", address);
        uriVariables.put("mobile", mobile);
        if (from == null) {
            uriVariables.put("from", 1);
        } else {
            uriVariables.put("from", from);
        }
        if (maxCount == null) {
            uriVariables.put("maxCount", 10);
        } else {
            uriVariables.put("maxCount", maxCount);
        }
        log.debug("发起远程http获取机构信息列表：{}=>{}", url, JSONUtil.parseObj(uriVariables));
        ResponseEntity<String> responseEntity = execute(url, null, HttpMethod.GET, MediaType.APPLICATION_JSON, null, uriVariables);
        String message = this.verify(responseEntity);
        if (StringUtils.isNotBlank(message)) {
            log.error("发起远程http获取机构信息列表：{}", message);
            return Result.fail(message);
        }
        JSONObject jsonObject = JSONUtil.parseObj(responseEntity.getBody());
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray jsonArray = data.getJSONArray("records");
        List<JiGouDTO> list = JSONUtil.toList(jsonArray, JiGouDTO.class);
        Page page = new Page(data.getLong("current"),data.getLong("size"));
        page.setRecords(list);
        page.setTotal(data.getLong("total"));
        return Result.success(page);
    }

	/**
	 * 互联互通编辑职工信息
	 * @param zhiGongDetailDTO 职工信息
	 * @return
	 */
	public Result<String> huLianHTZG(ZhiGongDetailDTO zhiGongDetailDTO) {
		String url = hospitalConfig.getUrl().getEditEmployeePath();
		String employee = JSONUtil.toJsonStr(JSONUtil.parseObj(zhiGongDetailDTO));
		log.debug("发起远程http 编辑职工信息：{}=>{}", url, employee);
		ResponseEntity<String> responseEntity = execute(url, null, HttpMethod.POST, MediaType.APPLICATION_JSON, employee, Maps.newHashMap());
		String message = this.verify(responseEntity);
		if (StringUtils.isNotBlank(message)) {
			log.error("发起远程http 编辑职工信息：{}", message);
			return Result.fail(message);
		}
		JSONObject jsonObject = JSONUtil.parseObj(responseEntity.getBody());
		String data = jsonObject.getStr("data");
		return Result.success(data);
	}

	/**
	 * 职工信息列表(互联互通专用)
	 * /jy/hospital/zhigong/page4Rhin
	 * @param zgGh 医疗卫生人员注册标识符
	 * @param status 医疗卫生人员可用状态
	 * @param name 医疗卫生人员姓名
	 * @param zcMc 职称名称
	 * @param zcDm 医疗卫生人员职称编码
	 * @param from 信息条目起始数
	 * @param maxCount 查询信息最大条数
	 * @param hospitalId 执业机构编码
	 * @return
	 */
	public Result<Page<ZhiGongDetailDTO>> page4Rhin(String zgGh, String status, String name, String zcMc, String zcDm,	Integer from, Integer maxCount, String hospitalId) {
		String url = hospitalConfig.getUrl().getSelectEmployeePath();
        Map<String, Object> uriVariables = Maps.newHashMap();
        uriVariables.put("zgGh", zgGh);
        uriVariables.put("status", status);
        uriVariables.put("name", name);
        uriVariables.put("zwDm", zcMc);
        uriVariables.put("zcDm", zcDm);
        uriVariables.put("hospitalId", hospitalId);
        if (from == null) {
            uriVariables.put("from", 1);
        } else {
            uriVariables.put("from", from);
        }
        if (maxCount == null) {
            uriVariables.put("maxCount", 10);
        } else {
            uriVariables.put("maxCount", maxCount);
        }
        log.debug("发起远程http获取职工信息列表：{}=>{}", url, JSONUtil.parseObj(uriVariables));
        ResponseEntity<String> responseEntity = execute(url, null, HttpMethod.GET, MediaType.APPLICATION_JSON, null, uriVariables);
        String message = this.verify(responseEntity);
        if (StringUtils.isNotBlank(message)) {
            log.error("发起远程http获取职工信息列表：{}", message);
            return Result.fail(message);
        }
        JSONObject jsonObject = JSONUtil.parseObj(responseEntity.getBody());
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray jsonArray = data.getJSONArray("records");
        List<ZhiGongDetailDTO> list = JSONUtil.toList(jsonArray, ZhiGongDetailDTO.class);
        Page page = new Page(data.getLong("current"),data.getLong("size"));
        page.setRecords(list);
        page.setTotal(data.getLong("total"));
        return Result.success(page);
    }

    /**
	 * 获取医院信息
	 * /jy/hospital/hospital/info
	 * @param hospitalId 医疗机构编码
	 * @return
	 */
    public Result<HospitalDTO> info(String hospitalId) {
        String url = hospitalConfig.getUrl().getFindOrgByIdPath();
        log.info("发起远程http获取医院信息：{}=>{}", url, hospitalId);
        Map<String, Object> uriVariables = Maps.newHashMap();
        uriVariables.put("hospitalId", hospitalId);
        ResponseEntity<String> responseEntity = execute(url, null, HttpMethod.GET, MediaType.APPLICATION_JSON, null, uriVariables);

        String message = this.verify(responseEntity);
        if (StringUtils.isNotBlank(message)) {
            log.error("发起远程http获取医院信息：{}", message);
            return Result.fail(message);
        }

        JSONObject jsonObject = JSONUtil.parseObj(responseEntity.getBody());
        JSONObject data = jsonObject.getJSONObject("data");
        HospitalDTO bean = JSONUtil.toBean(data, HospitalDTO.class);
        return Result.success(bean);
    }

    private String verify(ResponseEntity<String> responseEntity) {
        if (!super.isSuccess(responseEntity)) {
            return "请求状态不成功：" + responseEntity.getStatusCode();
        }

        String body = responseEntity.getBody();
        log.debug("response body {}", body);
        JSONObject jsonObject = JSONUtil.parseObj(body);

        String code = jsonObject.getStr("code");
        String msg = jsonObject.getStr("msg");
        if (!this.isSuccess(code)) {
            return StringUtils.join("业务状态不成功：", code, ":", msg);
        }
        return null;
    }

    private boolean isSuccess(String code) {
        return "1".equals(code);
    }

}
